<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
  <meta name="generator" content=
  "HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org">

  <title>count_if</title>
  <link href="../cppreference.css" rel="stylesheet" type="text/css">
</head>

<body>
<table>
  <tr>
  <td>
  <div class="body-content">

  <div class="header-box">
    <a href="../index.html">cppreference.com</a> &gt; <a href=
    "index.html">C++ Algorithms</a> &gt; <a href=
    "count_if.html">count_if</a>
  </div>

  <div class="name-format">
    count_if
  </div>

  <div class="syntax-name-format">
    Syntax:
  </div>
  <pre class="syntax-box">
  #include &lt;algorithm&gt;
  size_t count_if( iterator start, iterator end, UnaryPred p );
</pre>

  <p>The count_if() function returns the number of elements between
  <em>start</em> and <em>end</em> for which the predicate <em>p</em>
  returns true.</p>

  <p>For example, the following code uses count_if() with a predicate
  that returns true for the integer 3 to count the number of items in
  an array that are equal to 3:</p>
  <pre class="example-code">
 int nums[] = { 0, 1, 2, 3, 4, 5, 9, 3, 13 };
 int start = 0;
 int end = 9;           

 int target_value = 3;
 int num_items = count_if( nums+start,
                    nums+end,
                    bind2nd(equal_to&lt;int&gt;(), target_value) );             

 cout &lt;&lt; &quot;nums[] contains &quot; &lt;&lt; num_items &lt;&lt; &quot; items matching &quot; &lt;&lt; target_value &lt;&lt; endl;               
</pre>

  <p>When run, the above code displays the following output:</p>
  <pre class="example-code">
 nums[] contains 2 items matching 3             
</pre>

  <div class="related-name-format">
    Related topics:
  </div>

  <div class="related-content">
    <a href="count.html">count</a>
  </div>
  </div>
  </td>
  


  </tr>
  </table>
</body></html>
